package cn.orange.ch05_stack;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * LC496.下一个更大元素 I
 */
public class LC496 {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int n = nums1.length;
        int[] ans = new int[n];
        Arrays.fill(ans, -1);
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < n; i++) {
            map.put(nums1[i], i);
        }
        LinkedList<Integer> stk = new LinkedList<>();
        for (int i = 0; i < nums2.length; i++) {
            int num = nums2[i];
            while (!stk.isEmpty() && num > nums2[stk.peek()]) {
                Integer pop = stk.pop();
                if (map.containsKey(nums2[pop])) {
                    ans[map.get(nums2[pop])] = num;
                }
            }
            stk.push(i);
        }
        return ans;
    }

    public static void main(String[] args) {
        LC496 alg = new LC496();
        System.out.println(Arrays.toString(alg.nextGreaterElement(new int[]{4, 1, 2}, new int[]{1, 3, 4, 2})));
    }
}
